/**
 * Copyright (c) 2011-2014, homeant (homeanter@163.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package xin.homeant.upms.web.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


import xin.homeant.common.base.BaseController;
import xin.homeant.upms.app.service.IUserService;
import xin.homeant.upms.client.shiro.session.UpmsSession;
import xin.homeant.upms.client.shiro.session.UpmsSessionDao;
import xin.homeant.upms.common.constants.UpmsConstants;
import xin.homeant.upms.rpc.api.UpmsUserService;

/**
 * <P>
 * 用户登录控制器
 * </P>
 * 
 * @author homeant homeanter@163.com
 * @Data 2017年5月23日 下午1:23:55
 */
@Controller
public class LoginController extends BaseController {
	
	@Autowired
	private IUserService userService;
	
	@Autowired
    UpmsSessionDao upmsSessionDao;
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(HttpServletRequest request,Model model) {
		String backUrl = request.getParameter("redirect_uri");
		Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String sessionId = session.getId().toString();
        String id = userService.getServerSessionId(sessionId);
        if(StringUtils.isNotBlank(id)){
        	if(StringUtils.isNotBlank(backUrl)){
        		try {
					return "redirect:"+URLDecoder.decode(backUrl, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
        	}
        	return "redirect:manager/index";
        }
        model.addAttribute("redirect_uri",backUrl);
		return "login";
	}
	
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String login(HttpServletRequest request,ModelMap modelMap){
		String username = request.getParameter("username");
        String password = request.getParameter("password");
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String sessionId = session.getId().toString();
        String id = userService.getServerSessionId(sessionId);
        if(StringUtils.isBlank(id)){
        	try {
        		 // 使用shiro认证
                UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
                subject.login(usernamePasswordToken);
			} catch (UnknownAccountException e) {
				modelMap.put("error",  "帐号不存在！");
				return "login";
            } catch (IncorrectCredentialsException e) {
            	modelMap.put("error",  "密码错误！");
            	return "login";
            } catch (LockedAccountException e) {
            	modelMap.put("error",  "帐号已锁定！");
            	return "login";
            }
        	// 默认验证帐号密码正确，创建code
            String code = UUID.randomUUID().toString();
        	upmsSessionDao.updateStatus(sessionId, UpmsSession.OnlineStatus.on_line);
        	userService.addServerTicket(sessionId,code);
        	String backUrl = request.getParameter("redirect_uri");
        	if(StringUtils.isNotBlank(backUrl)){
        		try {
					return "redirect:"+URLDecoder.decode(backUrl, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
        	}
        	return "redirect:manager/index";
        }
		return "login";
	}
}
